iT邦幫忙

2025 iThome 鐵人賽

DAY 22
0
Software Development

通勤看手機就可讀懂的 Elixir 語言入門教學系列 第 22

Meta-programming 2 - 使用 unquote 帶入變數

  • 分享至 

  • xImage
  •  

除了直接使用 Code.eval_quoted 把表達試直接執行之外
寫巨集(macro)的時候,我們也會使用 Macro.to_string/1
來預先檢查目前寫的巨集

representation = quote do
  rem(9, 3)
end
Macro.to_string(representation)
#=> "rem(9, 3)"

但如果我今天想要使用 quote 外面的變數的話...

n = 99
representation = quote do
  rem(n, 3)
end
Macro.to_string(representation)
#=> "rem(n, 3)"

我們會發現,表達式保留的是 quote 裡面原本的樣子,
這樣子我們如果之後要使用這個表達式來寫巨集的時候,
每次都要準備好變數 n 相當不方便

unquote/1

這個時候我們可以使用 unquote/1n 包起來

n = 99
representation = quote do
  rem(unquote(n), 3)
end
Macro.to_string(representation)
#=> "rem(99, 3)"

上一篇
Meta-programming 1
下一篇
Meta-programming 3 - 定義巨集
系列文
通勤看手機就可讀懂的 Elixir 語言入門教學24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言